package itbour.onetouchshow.widget.inching;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;

import java.util.List;

import itbour.onetouchshow.R;
import itbour.onetouchshow.bean.canvas.CompoundPathsBean;
import itbour.onetouchshow.bean.canvas.PathsBean;
import itbour.onetouchshow.bean.canvas.PosBean;
import itbour.onetouchshow.bean.inching.noppt.InchingOutLineAllTypeV10Bean;
import itbour.onetouchshow.bean.inching.noppt.InchingOutLineImgBean;
import itbour.onetouchshow.bean.inching.noppt.InchingOutLineTableBean;
import itbour.onetouchshow.bean.inching.noppt.InchingOutLineTextOrShapeBean;
import itbour.onetouchshow.utils.CommonUtils;
import itbour.onetouchshow.utils.FineTuneRender;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.widget.InchingDottedView;

/**
 * Created by zjl_d on 2017/12/6.
 */

public class InchingOperaRelativeLayout extends RelativeLayout {
    public NewInchingFrontBoderView.UserTouchEventListener touchEventListener;
    private InchingOutLineAllTypeV10Bean data;
    private Context context;

    public InchingOperaRelativeLayout(Context context) {
        this(context, null);
    }

    public InchingOperaRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public InchingOperaRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;

    }

    /**
     * 设置固定的宽度，高度随之变化，使图片不会变形
     *
     * @param bm Bitmap
     * @return Bitmap
     */
    private static Bitmap scaleImage(Bitmap bm, int extractW, int extractH) {
        if (bm == null) {
            return null;
        }
        int width = bm.getWidth();
        int height = bm.getHeight();

        L_.e("scaleImage  ----width>" + width);
        L_.e("scaleImage  ----height>" + height);

        float scaleWidth = extractW * 1.0f / width;
        float scaleHeight = extractH * 1.0f / height;

        float max = Math.max(scaleWidth, scaleHeight);
        Matrix matrix = new Matrix();
        matrix.postScale(max, max);

        L_.e("scaleImage  ----extractH>" + extractH);
        L_.e("scaleImage  ----extractW>" + extractW);
        Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        L_.e("scaleImage  ----width>" + newBm.getWidth());
        L_.e("scaleImage  ----height>" + newBm.getHeight());
        if (!bm.isRecycled()) {
            bm.recycle();
            bm = null;
        }
        return newBm;
    }

    public void setData(InchingOutLineTextOrShapeBean data) {
        this.data = data;
    }

    public void setData(InchingOutLineTableBean data) {
        this.data = data;
    }

    public InchingOutLineAllTypeV10Bean getData() {
        return data;
    }

    public void setData(InchingOutLineImgBean data) {
        this.data = data;
    }

    public int getFineTuneRenderId() {
        if (data instanceof InchingOutLineTextOrShapeBean) {
            return ((InchingOutLineTextOrShapeBean) data).getId();

        } else if (data instanceof InchingOutLineImgBean) {
            return ((InchingOutLineImgBean) data).getId();

        } else if (data instanceof InchingOutLineTableBean) {
            return ((InchingOutLineTableBean) data).getId();

        }
        return -1;
    }

    public int getIsEnable() {
        if (data instanceof InchingOutLineTextOrShapeBean) {
            return ((InchingOutLineTextOrShapeBean) data).getEditable();

        } else if (data instanceof InchingOutLineImgBean) {
            return ((InchingOutLineImgBean) data).getEditable();

        } else if (data instanceof InchingOutLineTableBean) {
            return ((InchingOutLineTableBean) data).getEditable();

        }
        return -1;
    }

    public void moveThisView(int x, int y) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) getLayoutParams();
        lp.leftMargin = x;
        lp.topMargin = y;
        this.setLayoutParams(lp);

    }

    public void inControlMoveThisView(int w, int h) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) getLayoutParams();
        lp.width = w;
        lp.height = h;
        this.setLayoutParams(lp);
        postInvalidate();
    }

    /**
     * 设置虚线是否显示
     *
     * @param tag
     */
    public void setThisDottedLineIsShow(int tag) {
        InchingDottedView thisDottedLineView = getThisDottedLineView();
        if (thisDottedLineView == null) {
            return;
        }
        if (tag == 0) {
            thisDottedLineView.setVisibility(GONE);
        } else {
            thisDottedLineView.setVisibility(VISIBLE);
        }
    }

    /**
     * 获取虚线边框
     *
     * @return
     */
    public InchingDottedView getThisDottedLineView() {
        InchingDottedView viewById = this.findViewById(R.id.inching_dotted_line_view);
        return viewById;
    }

    public void setTouchEventListener(NewInchingFrontBoderView.UserTouchEventListener touchEventListener) {
        this.touchEventListener = touchEventListener;
    }


    /**
     * 用于抬手后的更新
     *
     * @param nowPageIndex
     * @param x
     * @param y
     * @param w
     * @param h
     * @param broad
     */
    public synchronized void upDateThisView(boolean isContrl, int nowPageIndex, int x, int y, int w, int h, NewInchingFrontBoderView broad) {
        InchingDottedView dottedView = this.findViewById(R.id.inching_dotted_line_view);
        if (data instanceof InchingOutLineTextOrShapeBean) {
            String dataJson = FineTuneRender.changeTextPositionForJava(nowPageIndex, ((InchingOutLineTextOrShapeBean) data).getId(), x, y, w, h);
            if (isContrl) {

            }
            long start = System.currentTimeMillis();
            InchingOutLineTextOrShapeBean inchingOutLineTextOrShapeBean = JSON.parseObject(dataJson, InchingOutLineTextOrShapeBean.class);
            long t2 = System.nanoTime();//收到响应的时间
            // TODO:
            long end = System.currentTimeMillis();
            L_.e("接收响应 JSON: function last time is " + (end - start) / 1000);
            setData(inchingOutLineTextOrShapeBean);
            InchingOperaViewImg img = this.findViewById(R.id.inching_can_opar_text);
            long start1 = System.currentTimeMillis();
            Bitmap bitmap = getTextOrShapBitMap((InchingOutLineTextOrShapeBean) data);
            long end1 = System.currentTimeMillis();
            L_.e("接收响应 bitmap: function last time is " + (end1 - start1) / 1000);
            int len = bitmap.getByteCount();
            img.setImageBitmap(bitmap);
            InchingOutLineTextOrShapeBean data = (InchingOutLineTextOrShapeBean) this.data;
            w = (int) data.getPos().getW();
            h = (int) data.getPos().getH();
            x = (int) data.getPos().getX();
            y = (int) data.getPos().getY();
            L_.i("upDateThisView===x" + x + "y===" + y + "w===" + w + "h===" + h);
            refreshViewAndChild(x, y, w, h, broad, img, dottedView);

        } else if (data instanceof InchingOutLineImgBean) {
            InchingOpreaImageView img = findViewById(R.id.inching_can_opear_img);

            img.setOnMaskChange(false, null, -1.0f, -1.0f);
            img.setNeedClip(true);
            InchingOutLineImgBean imgData = (InchingOutLineImgBean) data;
            L_.i("更新数据传入imgpos===" + x + "y===" + y + "w===" + w + "h===" + h);
            //如果是图片 需要保持不能变形的逻辑
            String dataJson = FineTuneRender.changeImagePositionForJava(nowPageIndex, (imgData).getId(), x, y, w, h, 0.0f);
            InchingOutLineImgBean newImgData = new Gson().fromJson(dataJson, InchingOutLineImgBean.class);
            setData(newImgData);
            String source = imgData.getSource();


            img.setData(newImgData);

            PosBean pos = ((InchingOutLineImgBean) (InchingOperaRelativeLayout.this.data)).getPos();
            w = (int) Math.ceil(pos.getW());
            h = (int) Math.ceil(pos.getH());
            x = (int) pos.getX();
            y = (int) pos.getY();

            int imgX = (int) newImgData.getImage().getX();
            int imgY = (int) newImgData.getImage().getY();
            L_.i("实际更新数据====" + x + "y===" + y + "w===" + w + "h===" + h + dataJson + "imgX===" + imgX + "imgY===" + imgY);

            refreshViewAndChildImg(x, y, w, h, broad, img, dottedView, imgX, imgY);

            Glide.with(context).asBitmap().load(source).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    int len = resource.getByteCount(); // 原始图片的byte[]数组大小
                    img.setImgBitmap(resource);

                }
            });


        } else if (data instanceof InchingOutLineTableBean) {
            String dataJson = FineTuneRender.changeTablePositionForJava(nowPageIndex, ((InchingOutLineTableBean) data).getId(), x, y, w, h, 0.0f);
            InchingOutLineTableBean tableBean = new Gson().fromJson(dataJson, InchingOutLineTableBean.class);
            setData(tableBean);
            InchingOperaViewImg table = this.findViewById(R.id.inching_can_opar_table);

            Bitmap bitmap = getTableBitMap((InchingOutLineTableBean) data);
            table.setImageBitmap(bitmap);

            InchingOutLineTableBean data = (InchingOutLineTableBean) this.data;
            w = (int) Math.ceil(data.getPos().getW());
            h = (int) Math.ceil(data.getPos().getH());
            x = (int) data.getPos().getX();
            y = (int) data.getPos().getY();
            refreshViewAndChild(x, y, w, h, broad, table, dottedView);

        }
    }

    /**
     * 用于刷新图片控件
     *
     * @param x
     * @param y
     * @param w
     * @param h
     * @param broad
     * @param img
     * @param dottedView
     * @param imgX
     * @param imgY
     */
    private void refreshViewAndChildImg(int x, int y, int w, int h, NewInchingFrontBoderView broad, InchingOpreaImageView img, InchingDottedView dottedView, int imgX, int imgY) {
        refreshView(x, y, w, h, broad);
        img.refreshInchingImageViewMask(imgX, imgY);
        img.refreshView(w, h);
        dottedView.refreshInchingDottedLineView(w, h);
    }

    /**
     * 用于刷新文字和表格
     *
     * @param x
     * @param y
     * @param w
     * @param h
     * @param broad
     * @param img
     * @param dottedView
     */
    private void refreshViewAndChild(int x, int y, int w, int h, NewInchingFrontBoderView broad, InchingOperaViewImg img, InchingDottedView dottedView) {

        refreshView(x, y, w, h, broad);
        img.refreshView(x, y, w, h);
        dottedView.refreshInchingDottedLineView(w, h);
    }

    private void refreshView(int x, int y, int w, int h, NewInchingFrontBoderView broad) {
        int cw = broad.mControllerWidth / 2;
        int ch = broad.mControllerHeight / 2;

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.width = w + cw;
        layoutParams.height = h + ch;
        layoutParams.topMargin = y;
        layoutParams.leftMargin = x;
        this.setLayoutParams(layoutParams);

        broad.refreshFontBoderView(0, 0, w, h);

    }

    public Bitmap getTextOrShapBitMap(InchingOutLineTextOrShapeBean data) {

        final int w = (int) Math.ceil(data.getPos().getW());
        final int h = (int) Math.ceil(data.getPos().getH());
        final int x = (int) data.getPos().getX();
        final int y = (int) data.getPos().getY();


        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        //绘制标识可编辑的虚线
        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#16D3CD")); //设置画笔颜色
        paint.setStrokeWidth(UIUtils.dp2px(1));//设置画笔宽度
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true);
//
//        //如果是不可编辑 那么不用可编辑的边框线
//        if (data.getEditable() == 1) {
//            PathEffect effects = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
//            paint.setPathEffect(effects);
////            横向第一条虚线
//            Path path = new Path();
//            path.moveTo(0, 0);
//            path.lineTo(0, canvas.getHeight());
//            path.lineTo(canvas.getWidth(), canvas.getHeight());
//            path.lineTo(canvas.getWidth(), 0);
//            path.close();
//            canvas.drawPath(path, paint);  //同一个path对象，只需要一个drawPath()
//
//        }
        //绘制文字路劲
        Path newPath = new Path();
        newPath.setFillType(Path.FillType.EVEN_ODD);


        Paint textPaint = new Paint();
        //如果拿不到颜色设置为透明
        if (data.getColor() == null) {
            textPaint.setColor(Color.TRANSPARENT);
        } else {
            textPaint.setColor(Color.rgb(data.getColor().getR(), data.getColor().getG(), data.getColor().getB()));
        }


        textPaint.setStrokeWidth(5);//设置画笔宽度
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setAntiAlias(true);
        //这里的onDraw画一组路径
        List<CompoundPathsBean> cp = data.getCp();
        for (int i = 0; i < cp.size(); i++) {
            List<PathsBean> paths = cp.get(i).getPaths();

            Path fontPath = CommonUtils.getTextOrShapeBesselPaths(paths);
            newPath.addPath(fontPath);
            canvas.drawPath(newPath, textPaint);
        }

        return bitmap;
        //return scaleImage(bitmap, w, h);
    }

    public Bitmap getTableBitMap(InchingOutLineTableBean tableBean) {
        PosBean tablePos = tableBean.getPos();
        //这里不加1会显示不完全
        int w = (int) Math.ceil(tablePos.getW());
        int h = (int) Math.ceil(tablePos.getH());
        int x = (int) tablePos.getX();
        int y = (int) tablePos.getY();

        //bitmap+1 让边界显示完全 但是实际宽高和返回值一致
        Bitmap bitmap = Bitmap.createBitmap(w + 1, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        //绘制标识可编辑的虚线
        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#16D3CD")); //设置画笔颜色
        paint.setStrokeWidth(UIUtils.dip2px(1));//设置画笔宽度
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true);


        List<InchingOutLineTextOrShapeBean> children = tableBean.getChildren();
        for (int i = 0; i < children.size(); i++) {
            InchingOutLineTextOrShapeBean data = children.get(i);
            PosBean pos = data.getPos();
            float cx = (int) pos.getX();
            float cy = (int) pos.getY();
            int cw = (int) ((pos.getW() > 0 && pos.getW() < 1) ? 1 : pos.getW());
            int ch = (int) pos.getH();


            Paint textPaint = new Paint();
            //如果拿不到颜色设置为透明
            if (data.getColor() == null) {
                textPaint.setColor(Color.TRANSPARENT);
            } else {
                textPaint.setColor(Color.rgb(data.getColor().getR(), data.getColor().getG(), data.getColor().getB()));
            }

            textPaint.setStrokeWidth(1);//设置画笔宽度
            textPaint.setStyle(Paint.Style.FILL);
            textPaint.setAntiAlias(true);
            //这里的onDraw画一组路径
            List<CompoundPathsBean> cp = data.getCp();
            for (int j = 0; j < cp.size(); j++) {

                Bitmap bitmapC = Bitmap.createBitmap(cw, ch, Bitmap.Config.ARGB_8888);
                Canvas canvaC = new Canvas(bitmapC);

                //绘制文字路劲
                Path newPath = new Path();
                newPath.setFillType(Path.FillType.EVEN_ODD);
                //问题在于 这里的path 是针对子控件的画布的宽高和偏移量
                List<PathsBean> paths = cp.get(j).getPaths();
                Path fontPath = CommonUtils.getTextOrShapeBesselPaths(paths);
                newPath.addPath(fontPath);
                canvaC.drawPath(newPath, textPaint);


                canvas.drawBitmap(bitmapC, cx, cy, textPaint);

            }
        }

        //return scaleImage(bitmap, w, h);
        return bitmap;
    }

    /**
     * 用于改字改图改表格后的更新
     *
     * @param allTypeData
     */
    public void chagneValueUpdate(InchingOutLineAllTypeV10Bean allTypeData) {
        NewInchingFrontBoderView broad = this.findViewById(R.id.inching_control);


        InchingDottedView dottedView = this.findViewById(R.id.inching_dotted_line_view);

        if (allTypeData instanceof InchingOutLineTextOrShapeBean) {
            InchingOperaViewImg img = findViewById(R.id.inching_can_opar_text);
            InchingOutLineTextOrShapeBean data = (InchingOutLineTextOrShapeBean) allTypeData;
            setData(data);
            Bitmap bitmap = getTextOrShapBitMap(data);
            img.setImageBitmap(bitmap);


            int w = (int) Math.ceil(data.getPos().getW());
            int h = (int) Math.ceil(data.getPos().getH());
            int x = (int) data.getPos().getX();
            int y = (int) data.getPos().getY();

            refreshViewAndChild(x, y, w, h, broad, img, dottedView);

        } else if (data instanceof InchingOutLineImgBean) {
            InchingOutLineImgBean data = (InchingOutLineImgBean) allTypeData;
            setData(data);
            InchingOpreaImageView imageView = findViewById(R.id.inching_can_opear_img);
            String source = data.getSource();
            Glide.with(context).asBitmap().load(source).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    imageView.setImgBitmap(resource);
                    imageView.setData(data);
                    imageView.postInvalidate();
                    PosBean pos = data.getPos();
                    int w = (int) Math.ceil(pos.getW());
                    int h = (int) Math.ceil(pos.getH());
                    int x = (int) pos.getX();
                    int y = (int) pos.getY();


                    int imgX = (int) data.getImage().getX();
                    int imgY = (int) data.getImage().getY();

                    refreshViewAndChildImg(x, y, w, h, broad, imageView, dottedView, imgX, imgY);
                }
            });

        } else if (data instanceof InchingOutLineTableBean) {
            InchingOperaViewImg img = findViewById(R.id.inching_can_opar_table);
            InchingOutLineTableBean data = (InchingOutLineTableBean) allTypeData;

            setData(data);

            Bitmap bitmap = getTableBitMap(data);
            img.setImageBitmap(bitmap);
            int w = (int) Math.ceil(data.getPos().getW());
            int h = (int) Math.ceil(data.getPos().getH());
            int x = (int) data.getPos().getX();
            int y = (int) data.getPos().getY();

            refreshViewAndChild(x, y, w, h, broad, img, dottedView);

        }
    }

    public void hideControlView() {

        NewInchingFrontBoderView viewById = findViewById(R.id.inching_control);
        viewById.setVisibility(GONE);

    }

    public void setControlViewShow() {
        NewInchingFrontBoderView viewById = findViewById(R.id.inching_control);
        viewById.setVisibility(VISIBLE);
        viewById.bringToFront();


    }

    private interface UserTouchEventListener {
        void onTouchEvent(MotionEvent event);
    }
}
